import { Observable } from "rxjs";
import { Injectable, Inject } from "@angular/core";
import { Resolve, ActivatedRouteSnapshot } from "@angular/router";
import { HttpClient } from "@angular/common/http";
import { ImgStoreData } from "src/storage/.config/store.type";
import { ServiceModule, urlApi } from "../../service.module";
import { pluck, map } from "rxjs/operators";

import config from "./../../../../storage/.config/store.config";

export interface AlbumResolveData {
  all: ImgStoreData["data"];
  this: ImgStoreData["data"][0];
  prev: ImgStoreData["data"][0] | null;
  next: ImgStoreData["data"][0] | null;
}

@Injectable({
  providedIn: ServiceModule
})
export class AlbumResolveService implements Resolve<AlbumResolveData> {
  constructor(private http: HttpClient, @Inject(urlApi) private url: string) {}

  resolve(route: ActivatedRouteSnapshot) {
    return this.getFileJson(route.params.name);
  }

  private getFileJson(name: string): Observable<AlbumResolveData> {
    const path = config.generate.filename;
    return this.http.get(`${this.url}/${path}`).pipe(
      pluck("data"),
      map((item: ImgStoreData["data"]) => this.filterMap(item, name))
    );
  }

  private filterMap(arr: ImgStoreData["data"], name: string): AlbumResolveData {
    let result: AlbumResolveData = {
      all: arr,
      this: null,
      prev: null,
      next: null
    };
    arr.forEach((v, k) => {
      if (v.name == name) {
        result.this = v;
        result.prev = arr[k - 1] ? arr[k - 1] : null;
        result.next = arr[k + 1] ? arr[k + 1] : null;
      }
    });

    return result;
  }
}
